﻿using System;
using System.Collections.Generic;

namespace Inovout.Gis
{
    public class SessionFactoryHolder
    {
        private static readonly SessionFactoryHolder instance = new SessionFactoryHolder();
        public static SessionFactoryHolder Instance
        {
            get { return instance; }
        }
        private SessionFactoryHolder()
        {
            gisConfigurationDictionaries = new Dictionary<object, Configuration>();
            gisSessionFactoryDictionaries = new Dictionary<Type, IGisSessionFactory>();
        }

        internal IGisSession CreateSession()
        {
            throw new NotImplementedException();
        }

        private readonly string defaultGisConfigurationKey = "DefaultGisRepository";
        private IDictionary<object, Configuration> gisConfigurationDictionaries;
        private IDictionary<Type, IGisSessionFactory> gisSessionFactoryDictionaries;
        public void RegisterConfiguration(Configuration config)
        {
            gisConfigurationDictionaries.Add(defaultGisConfigurationKey,config);
         }

        public Configuration GetConfiguration(object key)
        {
            Configuration config;
            if (!gisConfigurationDictionaries.TryGetValue(key, out config))
            {
                config=gisConfigurationDictionaries[defaultGisConfigurationKey];
                gisConfigurationDictionaries.Add(key,config);
            }
            return config;
        }

        public IGisSessionFactory GetSessionFactory(Type type)
        {
            IGisSessionFactory sessionFactory;
            if(!gisSessionFactoryDictionaries.TryGetValue(type, out sessionFactory))
            {
                Configuration confg = GetConfiguration(type);
                sessionFactory = confg.BuildSessionFactory();
                RegisterSessionFactory(type, sessionFactory);
            }
            return sessionFactory;
        }
        public void RegisterSessionFactory(Type type, IGisSessionFactory sessionFactory)
        {
            this.gisSessionFactoryDictionaries.Add(type, sessionFactory);
        }
    }
}
